package com.cheer.job;

import cn.hutool.core.date.DateUtil;
import com.cheer.enums.OaIntegralRuleEnum;
import com.cheer.service.OaIntegralService;
import com.cheer.utils.SpringContextUtil;

import java.util.Date;
import java.util.Objects;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * @author cheer
 */
public class OaLearnTask implements Delayed, Runnable {

    private static OaIntegralService oaIntegralService = SpringContextUtil.getBean(OaIntegralService.class);

    private Long expireTime;

    private String openid;

    private OaIntegralRuleEnum integralRuleEnum;

    private Integer itemsId;

    private Date createTime;

    public OaLearnTask(String openid, OaIntegralRuleEnum integralRuleEnum, Integer itemsId) {
        this.openid = openid;
        this.integralRuleEnum = integralRuleEnum;
        this.itemsId = itemsId;
        this.expireTime = DateUtil.currentSeconds() + 180;
        this.createTime = new Date();
    }

    @Override
    public long getDelay(TimeUnit unit) {
        return unit.convert(expireTime - DateUtil.currentSeconds(), TimeUnit.SECONDS);
    }

    @Override
    public void run() {
        oaIntegralService.add(openid, integralRuleEnum, itemsId, createTime);
    }

    @Override
    public int compareTo(Delayed o) {
        if (o == this) {
            return 0;
        }
        if (o instanceof OaLearnTask) {
            OaLearnTask other = (OaLearnTask) o;
            if (expireTime < other.expireTime) {
                return -1;
            } else if (expireTime > other.expireTime) {
                return 1;
            }
        }
        return 0;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        OaLearnTask learnTask = (OaLearnTask) o;
        return Objects.equals(expireTime, learnTask.expireTime) &&
                Objects.equals(openid, learnTask.openid) &&
                integralRuleEnum == learnTask.integralRuleEnum &&
                Objects.equals(itemsId, learnTask.itemsId) &&
                Objects.equals(createTime, learnTask.createTime);
    }

    @Override
    public int hashCode() {
        return Objects.hash(expireTime, openid, integralRuleEnum, itemsId, createTime);
    }

    public String getOpenid() {
        return openid;
    }

    public Date getCreateTime() {
        return createTime;
    }
}
